# _*_ coding utf-8 _*_
# FILENAME：operationTimeList.py
# DESCRIPTION: 作业时间管理
# AUTH: jarvis zhang
# DATE: 2022/5/31 10:53 上午
from PyQt5 import QtGui
from PyQt5.QtWidgets import *
from PyQt5.Qt import *
from sqlalchemy import desc
import qtawesome as qta
from components.BaseQueryWindow import BaseQueryWindow, CustomButtonDelegate
from constant import UploadType
from models.baseModel import get_session, delete
from models.operationTimeModel import OperationTimeModel
from views.log.uploadHandleLogView import UploadHandleLogWindow
from views.operationtime.operationTimeDetailList import OperationTimeDetailList
from views.operationtime.uploadDialog import UploadDialog
from views.operationtime.versionDialog import VersionDialog


class OperationTimeList(BaseQueryWindow):
    def __init__(self):
        super(OperationTimeList, self).__init__()
        self.__init_ui()

    ''' UI '''
    def __init_ui(self):
        # 隐藏运算日志、下载按钮
        self.toolBar.actions()[2].setVisible(False)
        self.toolBar.actions()[3].setVisible(False)

        # 信号槽连接
        self.btn_add.clicked.connect(self.add_click)
        self.btn_close.clicked.connect(self.close)
        self.btn_log.clicked.connect(self.upload_log_click)
        self.btn_refresh.clicked.connect(self.refresh)

    ''' Methods '''
    #  窗体show
    def show(self):
        super(OperationTimeList, self).show()
        self.setWindowTitle("作业时间管理")
        # 设置表头
        self.setTableViewHeaders()
        # 查询
        total = self.query_total(self.edit_vension.text())
        self.setTotalRecordCount(total)  # 总量
        self.recordQuery(0)  # page

        # 关闭窗体,释放资源
    def close(self):
        super(OperationTimeList, self).close()

    def setTableViewHeaders(self):
        self.tableeHeaderLabels = ['编号', '版本名称', '创建时间', '更新时间', '操作']
        self.dataModel.setHorizontalHeaderLabels(self.tableeHeaderLabels)
        # 设置列宽
        self.tableView.setColumnWidth(0, 50)
        self.tableView.setColumnWidth(1, 350)
        self.tableView.setColumnWidth(2, 150)
        self.tableView.setColumnWidth(3, 150)
        self.tableView.setColumnWidth(4, 250)
        #  设置代理按钮,[btnEdit, btnUpload, btnCal, btnView, btnDel]
        delegateBtnIsHiddes = [False, False, True, False, False, True]
        self.tableView.setItemDelegateForColumn(4, CustomButtonDelegate(self, delegateBtnIsHiddes))

    # 刷新
    def refresh(self):
        # 查询
        total = self.query_total(self.edit_vension.text())
        self.setTotalRecordCount(total)  # 总量
        self.recordQuery(0)  # page

    # 记录查询，重写
    def recordQuery(self, limitIndex):
        data = self.page(limitIndex, self.PageRecordCount, self.edit_no.text(), self.edit_vension.text())
        self.dataModel.clear()
        if len(data) > 0:
            for i in range(len(data)):
                # 添加
                newItem = QStandardItem(str(data[i].id))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 0, newItem)

                newItem = QStandardItem(str(data[i].version_name))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 1, newItem)

                newItem = QStandardItem(str(data[i].create_date))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 2, newItem)

                newItem = QStandardItem(str(data[i].update_date))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 3, newItem)

                newItem = QStandardItem("")
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 4, newItem)
        self.setTableViewHeaders()

    # 分页查询列表
    def page(self, limitIndex=0, pageRecordCount=0, no=0, version=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(OperationTimeModel)
        my_query = my_query.filter(OperationTimeModel.is_del == 0)
        # 拼接查询条件
        if version != "":
            my_query = my_query.filter(OperationTimeModel.version_name.like("%" + version + "%"))
        if no != "":
            my_query = my_query.filter(OperationTimeModel.id == no)
        # 拼接排序条件
        my_query = my_query.order_by(desc(OperationTimeModel.update_date))
        # 分页
        my_query = my_query.offset(limitIndex).limit(pageRecordCount)
        # 执行查询
        model = my_query.all()
        session.close()
        return model

    # 查询数据总量
    def query_total(self, version=None, factory=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(OperationTimeModel)
        my_query = my_query.filter(OperationTimeModel.is_del == 0)
        # 拼接查询条件
        if version:
            my_query = my_query.filter(OperationTimeModel.version_name == version)
        if factory:
            my_query = my_query.filter(OperationTimeModel.factory_id == factory)
        # 执行查询
        count = my_query.count()
        session.close()
        return count

    # 新增
    def add_click(self):
        VersionDialog.get_dialog(self)

    # 上传日志
    def upload_log_click(self):
        self.upload_log = UploadHandleLogWindow(type=UploadType.OPERATION_TIME.value)
        self.upload_log.show()

    # 编辑，继承父类
    def edit_click(self):
        super(OperationTimeList, self).edit_click()
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()
            VersionDialog.get_dialog(self, int(id))

    #  上传，继承父类
    def upload_click(self):
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()
            UploadDialog.get_dialog(self, id)
            print(row)

    #  查看，继承父类
    def view_click(self):
        print('view')
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()
            title = self.dataModel.item(row, 1).text()
            self.dialog = OperationTimeDetailList(int(id), title)
            self.dialog.show()

    # 删除，继承父类
    def del_click(self):
        choice = QMessageBox.question(self, '', '是否删除当前数据?', QMessageBox.Yes | QMessageBox.No)  # 1
        if choice == QMessageBox.Yes:  # 2
            button = self.sender()
            if button:
                cell = button.index
                row = cell[0]
                id = self.dataModel.item(row, 0).text()
                model = OperationTimeModel()
                model.id = int(id)
                delete(model)
                self.refresh()
        elif choice == QMessageBox.No:  # 4
            pass

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    MainWindow = OperationTimeList()
    MainWindow.show()
    sys.exit(app.exec_())